package stack.stackDefine;

/**
 * 链表实现栈
 * 启发：https://www.cnblogs.com/hapjin/p/4442729.html
 * @param <E>
 */
public class MyLinkedListStack<E> implements StackService<E> {
    private int size;
    private Node<E> first;
    private Node<E> rear;
    static class Node<E>{
        E item;
        Node<E> next;
        Node(E x){
            item = x;
        }
    }

    public E getFirst() {
        return first.item;
    }

    public E getRear() {
        return rear.item;
    }

    @Override
    public int getLength() {
        return size;
    }

    @Override
    public E pop() {
        if (size==1){
            E val = rear.item;
            first=null;
            rear=null;
            size--;
            return val;
        }
        Node<E> preNode = first;
        E val = rear.item;
        while (preNode.next!=rear){
            preNode = preNode.next;
        }
        preNode.next = null;
        rear = preNode;
        size--;
        return val;
    }

    @Override
    public void push(E e) {
        Node<E> node = new Node(e);
        if (size==0){
            first = node;
            rear = node;
            size++;
            return;
        }
        rear.next = node;
        rear = node;
        size++;
    }

    @Override
    public E peek() {
        return rear.item;
    }

    @Override
    public boolean empty() {
        return size==0;
    }

    @Override
    public void clear() {
        while (first!=null){
            pop();
        }
    }
    public void display(){
        Node<E> tmp = first;
        for (int i = 0; i < size; i++) {
            System.out.println(tmp.item);
            tmp = tmp.next;
        }
    }
}
